<template>
  <div>
    <el-checkbox v-model="expandAll" @change="handleExpandAll">展开/关闭</el-checkbox>
    <el-checkbox v-model="selectedAll" @change="handleselectedAll">全选/取消全选</el-checkbox>

    <el-tree
      ref="tree"
      style="width:300px;"
      :data="meunList"
      :props="defaultProps"
      show-checkbox
      node-key="id"
    />
    <button @click="doSave">确定</button>
  </div>
</template>
<script>
import {
  findAllPermissions as findAllPermissionsApi
} from '@/api/auth/source'
export default {
  name: 'Roles',
  mixins: [],
  data() {
    return {
      expandAll: false,
      selectedAll: false,
      defaultProps: {
        label: 'title',
        children: 'children'
      },
      meunList: [],
      selecetdIdAll: []
    }
  },
  computed: {
  },
  watch: {
    expandAll(newValue, oldValue) {

    },
    selectedAll(newValue, oldValue) {

    }
  },
  created() {
    this.getPermission()
  },
  mounted() {
  },
  methods: {
    doSave() {
      const tree = this.$refs.tree
      console.log('ids===>', tree.getCheckedKeys())
    },
    handleExpandAll(e) {
      console.log('e==>', e)
      console.log('tree==>', this.$refs.tree)
      const nodesMap = this.$refs.tree.store.nodesMap
      // if (e) {
      //   for (let i = 0; i < nodesMap.length; i++) {
      //     const item = nodesMap[i]
      //     item.expanded = true
      //   }
      // } else {
      //   for (let i = 0; i < nodesMap.length; i++) {
      //     const item = nodesMap[i]
      //     item.expanded = false
      //   }
      // }
      // for (let i = 0; i < nodesMap.length; i++) {
      //   const item = nodesMap[i]
      //   item.expanded = e
      // }

      for (const key in nodesMap) {
        const item = nodesMap[key]
        item.expanded = e
      }
    },
    handleselectedAll(e) {
      console.log('e==>', e)
      const tree = this.$refs.tree
      if (e) {
        this.getAllId(this.meunList)
        tree.setCheckedKeys(this.selecetdIdAll)
      } else {
        this.selecetdIdAll = []
        tree.setCheckedKeys([])
      }
    },
    getAllId(arr) {
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i]
        this.selecetdIdAll.push(item.id)
        if (item.children && item.children.length > 0) {
          this.getAllId(item.children)
        }
      }
    },
    async getPermission() {
      const res = await findAllPermissionsApi()
      const { success, data, message } = res
      if (success) {
        this.meunList = data.menus
      } else {
        this.$message.error(message)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
